import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/view_model/af_conversation_list_view_model.dart';
import 'package:badges/badges.dart' as badges;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dart_date/dart_date.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:go_router/go_router.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

class AfConversationListCell extends ConsumerWidget {
  const AfConversationListCell({
    super.key,
    required this.item,
  });
  final RCIMIWConversation item;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userInfo = ref
        .watch(getUserInfoFutureProvider(userId: item.targetId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );
    return Slidable(
      // Specify a key if the Slidable is dismissible.
      key: ValueKey(item.targetId ?? ""),

      // The start action pane is the one at the left or the top side.

      // The end action pane is the one at the right or the bottom side.
      endActionPane: ActionPane(
        extentRatio: 0.2,
        motion: const ScrollMotion(),
        children: [
          SlidableAction(
            onPressed: (_) {
              ref
                  .read(afConversationListServiceProvider.notifier)
                  .deleteConversation(targetId: item.targetId ?? '');
            },
            backgroundColor: const Color(0xffFF453A),
            foregroundColor: Colors.white,
            icon: Icons.delete,
          ),
        ],
      ),

      // The child of the Slidable is what the user sees when the
      // component is not dragged.
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          AFLogPvManger.stat(page: AFLogPages.tabChat);
          context.pushNamed(RouteUri.messageDetai,
              queryParams: {"userId": item.targetId ?? ''});
        },
        child: Container(
          decoration: const BoxDecoration(
            color: Colors.white,
          ),
          padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Flexible(
                child: Row(
                  children: [
                    SizedBox(
                      height: 44,
                      child: badges.Badge(
                        position: badges.BadgePosition.topEnd(top: -3, end: -3),
                        showBadge: (item.unreadCount ?? 0) > 0,
                        ignorePointer: false,
                        badgeContent: Text(
                          '${item.unreadCount ?? 0}',
                          style: const TextStyle(
                            color: Color(0xffffffff),
                            fontWeight: FontWeight.normal,
                            fontSize: 10,
                          ),
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(22),
                          child: AspectRatio(
                            aspectRatio: 1,
                            child: CachedNetworkImage(
                              imageUrl: userInfo?.avatarUrl ?? '',
                              fit: BoxFit.fill,
                              placeholder: (context, url) => const Material(
                                color: Color(0xffF2F5F9),
                                child: Center(
                                  child: SizedBox(
                                    width: 25,
                                    height: 25,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      color: Color(0xffADADAD),
                                      backgroundColor: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                              errorWidget: (context, url, error) =>
                                  const CircularProgressIndicator(
                                strokeWidth: 2,
                                color: Color(0xffADADAD),
                                backgroundColor: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Flexible(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            userInfo?.nickname ?? '',
                            style: const TextStyle(
                              color: Color(0xff202020),
                              fontWeight: FontWeight.normal,
                              fontSize: 14,
                            ),
                            textAlign: TextAlign.left,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          ),
                          const SizedBox(
                            height: 5,
                          ),
                          Text(
                            item.lastMessage?.conversationMsgStr ?? '',
                            style: TextStyle(
                              color: const Color(0xff000000).withOpacity(0.3),
                              fontWeight: FontWeight.normal,
                              fontSize: 12,
                            ),
                            textAlign: TextAlign.left,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          )
                        ],
                      ),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 10, top: 0, left: 5),
                child: Text(
                  item.showTime,
                  style: TextStyle(
                    color: const Color(0xff000000).withOpacity(0.3),
                    fontWeight: FontWeight.normal,
                    fontSize: 10,
                  ),
                  textAlign: TextAlign.right,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

extension RCIMIWMessageExt on RCIMIWMessage {
  String get conversationMsgStr {
    final message = this;
    if (message is RCIMIWTextMessage) {
      return message.text ?? '';
    } else if (message is RCIMIWVoiceMessage) {
      return '''[Voice] ${message.duration}"''';
    } else if (message is RCIMIWImageMessage) {
      return '''[Picture]''';
    } else if (message is RCIMIWFileMessage) {
      return '''[File]''';
    } else {
      return "'''[Message]'''";
    }
  }
}

extension RCIMIWConversationExt on RCIMIWConversation {
  String get showTime {
    if (operationTime != null) {
      var date = DateTime.fromMillisecondsSinceEpoch(operationTime!);
      if (date.isToday) {
        return date.format("HH:mm");
      } else if (date.isSameYear(DateTime.now())) {
        return date.format("MM-dd HH:mm");
      } else {
        return date.format("yyyy-MM-dd");
      }
    } else {
      return '';
    }
  }
}
